package cn.onesdream.app.api.security;

import cn.onesdream.app.api.service.Impl.UserServiceImpl;
import cn.onesdream.app.dao.entity.Role;
import cn.onesdream.app.dao.entity.User;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author
 */
@Api("自定义在服务器上根据用户名读取用户信息")
@Service
public class AppUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserServiceImpl userServiceImpl;


    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        User user = userServiceImpl.getUserByAccount(account);
        List<Role> roleList = userServiceImpl.getRoleByAccount(account);
        List<GrantedAuthority> authorityList = new ArrayList<>();
        for(Role role: roleList){
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role.getName());
            authorityList.add(simpleGrantedAuthority);
        }
        user.setAuthorities(authorityList);
        UserDetails userDetails = user;
        return userDetails;
    }

}
